package com.java.star.mall.front.filter;

import com.alibaba.fastjson2.JSON;
import com.java.star.mall.common.constant.web.HttpConstant;
import com.java.star.mall.common.constant.web.JwtConstant;
import com.java.star.mall.common.response.JsonResult;
import com.java.star.mall.common.response.StatusCode;
import com.java.star.mall.front.pojo.authentication.CurrentPrincipal;
import com.java.star.mall.front.properties.JwtProperties;
import com.java.star.mall.front.util.CurrentPrincipalUtils;
import com.java.star.mall.front.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 认证过滤器
 * 该过滤器只会过滤某些需要进行登录认证的请求
 * 可以查看如下类中的配置来确定需要过滤的请求是哪些
 *
 * @see com.java.star.mall.front.config.WebMvcConfiguration
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 过滤方法
     *
     * @param request     当前请求对象
     * @param response    当前响应对象
     * @param filterChain 过滤器链
     * @throws ServletException Servlet异常
     * @throws IOException      IO异常
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //1.从请求头中获取jwt信息
        String jwt = request.getHeader(HttpConstant.HEADER_AUTHORIZATION);
        log.debug("客户端携带的JWT：{}", jwt);

        //2.判断jwt的有效性
        if (!StringUtils.hasText(jwt) || jwt.length() < JwtConstant.JWT_MIN_LENGTH) {
            writeResponse(response, StatusCode.JWT_UNAUTHORIZED_ERROR);
            return;
        }

        //3.解析JWT数据
        Claims claims;
        try {
            claims = JwtUtils.parse(jwt, jwtProperties.getSecretKey());
        } catch (ExpiredJwtException e) {
            writeResponse(response, StatusCode.JWT_EXPIRED_ERROR);
            return;
        } catch (SignatureException e) {
            writeResponse(response, StatusCode.JWT_SIGNATURE_ERROR);
            return;
        } catch (MalformedJwtException e) {
            writeResponse(response, StatusCode.JWT_MALFORMED_ERROR);
            return;
        } catch (Throwable e) {
            e.printStackTrace();
            writeResponse(response, StatusCode.SYSTEM_ERROR);
            return;
        }

        //4.获取解析数据
        Integer userId = claims.get(JwtConstant.CLAIM_USER_ID, Integer.class);
        String openId = claims.get(JwtConstant.CLAIM_OPEN_ID, String.class);
        log.debug("用户ID为：{}", userId);
        log.debug("openID为：{}", openId);

        //5.设置当前登录用户
        CurrentPrincipal currentPrincipal = new CurrentPrincipal();
        currentPrincipal.setId(userId);
        currentPrincipal.setOpenId(openId);
        CurrentPrincipalUtils.setCurrentPrincipal(currentPrincipal);

        try {
            filterChain.doFilter(request, response);
        } finally {
            /*
             * 无论是否执行成功，都将CurrentPrincipalUtils中的ThreadLocal进行一次清空
             * 这里是为了防止Tomcat线程池的复用，导致数据出现异样
             */
            log.debug("清空ThreadLocal...");
            CurrentPrincipalUtils.removeCurrentPrincipal();
        }
    }

    /**
     * IO写出响应数据
     *
     * @param response 当前响应对象
     * @throws IOException IO异常
     */
    private void writeResponse(HttpServletResponse response, StatusCode statusCode) throws IOException {
        response.setContentType(HttpConstant.JSON_CONTENT_TYPE);
        JsonResult<Void> jsonResult = JsonResult.fail(statusCode);
        try (PrintWriter writer = response.getWriter()) {
            writer.println(JSON.toJSONString(jsonResult));
        }
    }
}
